﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using ASPNETPerformance.App_BusinessLogic.Helpers;

namespace ASPNETPerformance.App_BusinessLogic.Image {
    public class ImageManager {
        private static readonly object s_lock = new object();

        public static string GetPictureUrl( string fileName, int height, int width, bool showDefault ) {
            string url = string.Empty;
            string localFilename = string.Empty;

            if ( string.IsNullOrEmpty( fileName ) || height == 0 || width == 0 || showDefault ) {
                return url;
            }

            FileInfo fi = new FileInfo( LocalImagePath + "\\" + fileName );
            if ( fi.Exists ) {
                int index = fileName.LastIndexOf( "." ) + 1;
                string extension = fileName.Substring( index );
                localFilename = fi.Name.Replace( "." + extension, "" );

                lock ( s_lock ) {
                    localFilename = string.Format( "{0}_x{1}_x{2}.{3}", localFilename, height, width, extension );
                    if ( !File.Exists( Path.Combine( LocalThumbImagePath, localFilename ) ) ) {
                        if ( !System.IO.Directory.Exists( LocalThumbImagePath ) ) {
                            System.IO.Directory.CreateDirectory( LocalThumbImagePath );
                        }

                        using ( MemoryStream stream = new MemoryStream( File.ReadAllBytes( fi.FullName ) ) ) {
                            var b = new Bitmap( stream );

                            var newBitMap = new Bitmap( width, height );
                            var g = Graphics.FromImage( newBitMap );
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                            g.DrawImage( b, 0, 0, width, height );

                            //配置JPEG压缩引擎
                            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                            long[] quality = new long[ 1 ];
                            quality[ 0 ] = 100L;
                            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality );
                            encoderParams.Param[ 0 ] = encoderParam;

                            string mimeType = "image/jpeg";
                            switch ( extension ) {
                                case "jpg":
                                case "jpeg":
                                    mimeType = "image/jpeg";
                                    break;
                                case "png":
                                    mimeType = "image/png";
                                    break;
                                case "gif":
                                    mimeType = "image/png";
                                    break;
                                default:
                                    mimeType = "image/jpeg";
                                    break;
                            }

                            System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
                            System.Drawing.Imaging.ImageCodecInfo jpegICI = null;
                            for ( int x = 0; x < arrayICI.Length; x++ ) {
                                if ( arrayICI[ x ].MimeType.Equals( mimeType, StringComparison.OrdinalIgnoreCase ) ) {
                                    jpegICI = arrayICI[ x ];
                                    break;
                                }
                            }

                            newBitMap.Save( Path.Combine( LocalThumbImagePath, localFilename ), jpegICI, encoderParams );
                            newBitMap.Dispose();
                            b.Dispose();
                        }
                    }
                }
            }

            url = CommonHelper.GetDemosLocation() + "_assets/img/thumbs/" + localFilename;
            return url;
        }

        public static string GetBase64Image( string imgPath ) {
            string dataType = string.Empty;

            switch ( imgPath.ToLower().Substring( imgPath.Length - 4, 4 ) ) {
                case ".jpg":
                    dataType = "image/jpeg";
                    break;
                case ".gif":
                    dataType = "image/gif";
                    break;
                case ".png":
                    dataType = "image/png";
                    break;
                case ".htm":
                    dataType = "text/html";
                    break;
                case ".css":
                    dataType = "text/css";
                    break;
                default:
                    break;
            }

            return string.Format( "data:{0};base64,{1}", dataType, Convert.ToBase64String( File.ReadAllBytes( imgPath ) ) );
        }

        public static void RemoveSpriteImageOptimizationModule() {
            try {
                string path1 = HttpContext.Current.Server.MapPath( "~/_assets/img/Sprites/highCompat.css" );
                if ( System.IO.File.Exists( path1 ) ) {
                    System.IO.File.Delete( path1 );
                }

                string path2 = HttpContext.Current.Server.MapPath( "~/_assets/img/Sprites/lowCompat.css" );
                if ( System.IO.File.Exists( path2 ) ) {
                    System.IO.File.Delete( path2 );
                }

                string path3 = HttpContext.Current.Server.MapPath( "~/_assets/img/Sprites/sprite0.css" );
                if ( System.IO.File.Exists( path3 ) ) {
                    System.IO.File.Delete( path3 );
                }

                string path4 = HttpContext.Current.Server.MapPath( "~/_assets/img/Sprites/timeStamp.css" );
                if ( System.IO.File.Exists( path4 ) ) {
                    System.IO.File.Delete( path4 );
                }
            }
            catch( Exception ex ) {
            }
        }

        public static string LocalThumbImagePath {
            get {
                string path = HttpContext.Current.Request.PhysicalApplicationPath + "_assets\\img\\thumbs";
                return path;
            }
        }

        public static string LocalImagePath {
            get {
                string path = HttpContext.Current.Request.PhysicalApplicationPath + "_assets\\img";
                return path;
            }
        }
    }
}